<template>
  <div class="class-order">
    <!-- 统计表格 -->
    <h2>班级订单总计</h2>
    <table v-if="classOrderSummary">
      <thead>
        <tr>
          <th>书名</th>
          <th>作者</th>
          <th>类别</th>
          <th>描述</th>
          <th>价格</th>
          <th>总数量</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="book in classOrderSummary" :key="book.name">
          <td>{{ book.name }}</td>
          <td>{{ book.author }}</td>
          <td>{{ book.category }}</td>
          <td>{{ book.description }}</td>
          <td>{{ book.price }}元</td>
          <td>{{ book.totalQuantity }}</td>
        </tr>
      </tbody>
    </table>

    <h2>班级订单</h2>
    <div v-if="classOrders.length === 0">没有订单记录</div>
    <div v-else class="order-list">
      <div v-for="order in classOrders" :key="order.id" class="order-container">
        <h3>订单号: {{ order.id }}</h3>
        <p>学生姓名: {{ order.student_name }}</p>
        <p>班级: {{ order.class_name }}</p>
        <p>学期: {{ order.semester_name }}</p>
        <p>下单时间: {{ formatDateTime(order.created_at) }}</p>
        <p>总金额: {{ order.total_amount }}元</p>
        <p v-if="order.remark">备注: {{ order.remark }}</p>

        <button @click="toggleOrderDetails(order)">
          {{ order.showDetails ? '收起' : '查看详细信息' }}
        </button>

        <!-- 懒加载订单详细信息 -->
        <div v-if="order.showDetails && order.order_details && order.order_details.length > 0" class="order-books">
          <table>
            <thead>
              <tr>
                <th>学生姓名</th>
                <th>书名</th>
                <th>作者</th>
                <th>类别</th>
                <th>描述</th>
                <th>价格</th>
                <th>数量</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="book in order.order_details" :key="book.id">
                <td>{{ order.student_name }}</td>
                <td>{{ book.materialInfo.name }}</td>
                <td>{{ book.materialInfo.author }}</td>
                <td>{{ book.materialInfo.category }}</td>
                <td>{{ book.materialInfo.description }}</td>
                <td>{{ book.materialInfo.price }}元</td>
                <td>{{ book.quantity }}</td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import axios from 'axios';

export default {
  name: 'ClassOrder',
  setup() {
    const classOrders = ref([]);
    const classOrderSummary = ref([]);
    const loading = ref(false);
    const error = ref(null);

    const formatDateTime = (dateString) => {
      const date = new Date(dateString);
      const cstDate = new Date(date.getTime() + 8 * 60 * 60 * 1000); // 加8小时
      const year = cstDate.getFullYear();
      const month = String(cstDate.getMonth() + 1).padStart(2, '0');
      const day = String(cstDate.getDate()).padStart(2, '0');
      const hours = String(cstDate.getHours()).padStart(2, '0');
      const minutes = String(cstDate.getMinutes()).padStart(2, '0');
      const seconds = String(cstDate.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    };

    const fetchLearningMaterialInfo = async (learningMaterialId) => {
      try {
        const response = await axios.get(`/api/v1/learning_material/info`, {
          params: { id: learningMaterialId }
        });
        if (response.data.code === 200) {
          return response.data.data; // 返回图书详细信息
        } else {
          console.error("获取图书信息失败:", response.data.msg);
          return null;
        }
      } catch (error) {
        console.error(`获取图书信息 ${learningMaterialId} 的详细信息失败:`, error);
        return null;
      }
    };

    const fetchOrderDetails = async (order) => {
      try {
        const response = await axios.get(`/api/v1/order/info`, {
          params: { id: order.id }
        });
        if (response.data.code === 200) {
          const orderDetails = response.data.data;
          const learningMaterials = await Promise.all(orderDetails.order_details.map(async (detail) => {
            const materialInfo = await fetchLearningMaterialInfo(detail.learning_material_id);
            return { ...detail, materialInfo };
          }));
          order.order_details = learningMaterials;
        } else {
          console.error("获取订单详细信息失败:", response.data.msg);
        }
      } catch (error) {
        console.error(`获取订单 ${order.id} 的详细信息失败:`, error);
      }
    };

    const fetchClassOrders = async () => {
      try {
        loading.value = true;
        error.value = null;
        const user = JSON.parse(localStorage.getItem('user'));
        const classId = user.classId;
        const response = await axios.get('/api/v1/order/list_self_class', {
          params: { classId },
          withCredentials: true,
        });
        classOrders.value = response.data.data.map(order => ({
          ...order,
          showDetails: false,
          created_at: formatDateTime(order.created_at),
          order_details: [] // 先初始化为空数组，后续填充
        }));

        // 确保所有订单详情都加载完成后再进行统计计算
        await Promise.all(classOrders.value.map(order => fetchOrderDetails(order).catch(err => {
          console.error(`获取订单 ${order.id} 的详细信息失败:`, err);
          return []; // 如果某个订单详情获取失败，返回空数组
        })));

        const allBooks = classOrders.value.flatMap(order => order.order_details);
        const summary = allBooks.reduce((acc, book) => {
          const existingBook = acc.find(b => b.materialInfo.name === book.materialInfo.name);
          if (existingBook) {
            existingBook.quantity += book.quantity;
          } else {
            acc.push({ ...book, quantity: book.quantity });
          }
          return acc;
        }, []);

        classOrderSummary.value = summary.map(book => ({
          name: book.materialInfo.name,
          author: book.materialInfo.author,
          category: book.materialInfo.category,
          description: book.materialInfo.description,
          price: book.materialInfo.price,
          totalQuantity: book.quantity
        }));
      } catch (err) {
        error.value = err.message;
      } finally {
        loading.value = false;
      }
    };


    const toggleOrderDetails = async (order) => {
      if (!order.showDetails) {
        await fetchOrderDetails(order);
      }
      order.showDetails = !order.showDetails;
    };

    onMounted(fetchClassOrders);

    return {
      classOrders,
      classOrderSummary,
      loading,
      error,
      formatDateTime,
      toggleOrderDetails
    };
  },
};
</script>

<style>
.class-order {
  padding: 20px;
}

.order-list {
  display: flex;
  flex-direction: column;
}

.order-container {
  border: 1px solid #ccc;
  padding: 10px;
  margin-bottom: 10px;
}

.order-books {
  margin-top: 10px;
}

.book-item {
  margin-bottom: 10px;
  padding: 5px;
  border: 1px solid #ddd;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th,
td {
  border: 1px solid #ddd;
  padding: 8px;
  text-align: left;
}

th {
  background-color: #f2f2f2;
}

tr:nth-child(even) {
  background-color: #f9f9f9;
}

tr:hover {
  background-color: #f1f1f1;
}
</style>